package com.haidao.admin.component.api;

import feign.Feign;
import feign.Logger;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lyy
 */
public class ApiManager {

    private final Map<Class<?>, Object> cache = new ConcurrentHashMap<>();

    private Properties properties = new Properties();

    public <T> T getApi(Class<T> clazz) {
        if (!cache.containsKey(clazz)) {
            HttpClient clientAnn = clazz.getAnnotation(HttpClient.class);
            if (clientAnn == null) {
                throw new IllegalArgumentException(String.format("%s must annotation width %s", clazz, HttpClient.class));
            }
            String url = properties.getProperty(clientAnn.key());
            if (StringUtils.isEmpty(url)) {
                url = System.getProperty(clientAnn.key());
            }
            if (StringUtils.isEmpty(url)) {
                url = clientAnn.defUrl();
            }
            T t = Feign.builder()
                    .logLevel(Logger.Level.FULL)
                    .encoder(new JacksonEncoder())
                    .decoder(new JacksonDecoder())
                    .target(clazz, url);
            cache.put(clazz, t);
        }
        return (T) cache.get(clazz);
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }
}